/**
 * 添加采购单modal
 */

'use strict';

var React = require('react-native');
var {msg} = require('iflux-native');
var fetch = require('../fetch');
var QMConst = require('../const');
var QMLoading = require('../loading');
var SpecList = require('./spec-list');
var Button = require('./button');
var AlertAndroid = require('../alert');

var {
  StyleSheet,
  View,
  Text,
  Image,
  Platform,
  AlertIOS,
  StatusBarIOS,
  InteractionManager,
  PixelRatio, 
  TouchableOpacity
} = React;

var Alert = Platform.OS === 'ios' ? AlertIOS : AlertAndroid;


// just do nothing
var noop = () => {};


/**
 * 详情
 */
var GoodsDetail = React.createClass({
  getDefaultProps(){
    return {
      /*商品id*/
      spuId: '',
      /*货品id*/
      skuId: '',
      onHide: noop,
      /*来源，现在就在值为shelf时有特殊操作*/
      source: ''
    }
  },


  getInitialState() {
    return {
      /*当前loading的状态*/
      isLoading: false,
      /*商品的缩略图*/
      img: '',
      /*商品名称*/
      name: '',
      /*商品编号*/
      bn: '',
      /*单位*/
      unit: '',
      specs: [],
      /*市场价*/
      mktPrice: null,
      /*区间价*/
      priceRange: null,
      /*当前选中的除去最后一个规格的规格组合*/
      skuProps: [],
      /*sku最后一个规格的可选值*/
      skuLastProps: [],
      /*最后一个规格对应的sku*/
      skus: [],
      /*正常规格数量，当数量为0禁用添加采购单按钮*/
      enableSpec: [],
      /*是否收藏*/
      isShelf: false,
      /*一进来的是否收藏状态*/
      defaultIsShelf: false,
      /*购物车商品数量*/
      cartCount: 0
    };
  },


  /**
   * 获取数据
   */
  componentDidMount() {
    InteractionManager.runAfterInteractions(() => {
      if(__DEV__) {
        console.log('等到所有的动画结束才去加载数据...');
      }
      fetch(`${QMConst.HOST}/goods/detail/${this.props.spuId}`)
        .then((res) => {
          if (__DEV__) {
            console.log('获取商品详情数据:', res);
          }

          //过滤sku的组合
          this._cache = [];
          //缓存规格组合和
          this._allSkuCache = {};
          //缓存sku组合
          var skus = new Array();

          res.mkts.forEach((v) => {
            var specValList = v.props.map((v) => v.split('-')[1]);
            this._allSkuCache[specValList.join('-')] = v;
            this._cache.push(specValList);
          });

          if (__DEV__) {
            console.log('缓存规格组合数据');
            console.table(this._cache);
            console.log('缓存规格组合和sku的映射', this._allSkuCache);
          }

          //过滤出当前的sku信息
          var sku;
          // 如果商品编号和货品编号相等，说明列表是商品列表，这里直接取第一个货品
          if (this.props.skuId == this.props.spuId) {
            sku = res.mkts[0];
          } else {
            sku = res.mkts.filter((v) => v.skuId === this.props.skuId)[0];
          }

          if(res.mkts.length > 0 && !sku){
            sku = res.mkts[0];
          }

          if (res.mkts.length < 1 || !sku) {
            msg.emit('app:tip', '商品已下架');
            msg.emit('route:backToLast');
          } else {
            var skuProps = sku.props.slice(0, -1).map((v) => {
              return v.split('-')[1];
            });

            // 拼接规格
            var spec_str = skuProps.join('-');
            // 最后一个规格的可选值
            var skuLastProps = this._filterSkuLastSpecList(skuProps);

            skuLastProps.forEach((lastSpec, k) => {

              var specStr = lastSpec;
              if ('' != spec_str.trim()) {
                specStr = spec_str + '-' + lastSpec;
              }

              var sku_obj = this._allSkuCache[specStr];
              if (sku_obj) {
                skus[k] = sku_obj;
              }
            });

            if (__DEV__) {
              console.log('商品集合', skus);
              console.log('当前的sku组合：', skuProps);
              console.log('最后一个规格的可选值:', skuLastProps);
            }

            // 设置禁用规格
            var props = res.specs;
            var enableSpec = new Array();
            if (skuProps.length) {
              props = this._setSpecDisable(skuProps, skuLastProps, res.specs, enableSpec);
            } else {
              skus.forEach((item, index) => {
                if (item.disable == 1) {
                  enableSpec.push(item);
                }
              });
            }

            this.setState({
              isLoading: true,
              unit: res.det.unit,
              img: res.det.img,
              bn: res.det.bn,
              name: res.det.name,
              mktPrice: res.det.mktpr,
              priceRange: res.det.pricereg,
              isShelf: res.det.isfav,
              defaultIsShelf: res.det.isfav,
              specs: props,
              skuProps: skuProps,
              skuLastProps: skuLastProps,
              skus: skus,
              enableSpec: enableSpec
            });
          }
        });
      // 刷新加入采购单购物车数量
      this._handleRefreshCount();
    });
  },


  /**
   * 还原StatusBar
   */
  componentWillUnmount(){
    if (Platform.OS === 'ios') {
      StatusBarIOS.setHidden(false);
    }
  },


  render() {
    return this._renderContent();
  },


  _renderContent() {
    return (
      <View style={styles.innerContainer}>
        {this.state.isLoading ? this._renderDetail() : <QMLoading/>}
      </View>
    );
  },


  _renderDetail() {
    return (
      <View style={{flex: 1}}>
        <View style={styles.listRow}>
          {/*商品图片*/}
          <Image style={styles.img} source={{uri: this.state.img}} />

          <View style={styles.detail}>
            <View style={{flex: 1}}>
              <View style={{flex: 2}}>
                {/*商品编号*/}
                <Text style={{paddingBottom: 2,fontSize: 14, color: '#bbc1c6'}}>{this.state.bn}</Text>
                {/*商品名称*/}
                <Text style={styles.proText}>
                  {this.state.name}
                </Text>
                {/*商品市场价*/}
                <Text style={{fontSize: 12, color: '#bbc1c6'}}>{this.state.mktPrice == '' ? '' : '市场价 ¥' + this.state.mktPrice}</Text>
              </View>
            </View>
            {/*商品区间价格*/}
            <View style={[styles.proCart]}>
              <Text style={styles.priceText}>
                {this.state.priceRange && '￥' + this.state.priceRange}
              </Text>
            </View>
          </View>
        </View>

        {/*规格列表*/}
        <SpecList
          ref='specList'
          unit={this.state.unit}
          productName={this.state.name}
          onSelectSpec={this._handleSelectSpec}
          skuLastProps={this.state.skuLastProps}
          skuProps={this.state.skuProps}
          dataSource={this.state.specs}
          skus={this.state.skus}/>

        <Button
          onPress={this._handleAddShoppingCart}
          onShelfPress={this._handleEditShelf}
          disabled={this.state.enableSpec.length}
          isShelf={this.state.isShelf}
          cartCount={this.state.cartCount}
        />
      </View>
    );
  },


  /**
   * 关闭
   */
  _handleClose() {
    msg.emit('route:backToLast');
  },


  /**
   * 添加采购单
   */
  _handleAddShoppingCart() {
    var result = this._getShoppingCartData();

    if (parseInt(result["total"]) <= 0) {
      msg.emit('app:tip', '商品数量不能全部为0');
      return;
    }

    if (__DEV__) {
      console.log('提交的数据:', result["submitData"]);
    }

    fetch(`${QMConst.HOST}/cart/add`, {
      method: 'POST',
      body: JSON.stringify(result["submitData"])
    }).then((res) => {
      msg.emit('app:tip', '成功加入采购单');

      //跳转到订单确认页
      // 刷新采购单
      msg.emit('cart:refresh');
      //刷新home采购单的数量
      msg.emit('refreshCartCount');
      msg.emit('pop-up-close');
    });
  },


  /**
   * 修改收藏
   * @private
   */
  _handleEditShelf(){
    var isShelf = this.state.isShelf;
    var productId = this.props.spuId;
    var goodsId = this.state.skus[0].skuId;

    var url = `${QMConst.HOST}/goods/addShelf?productId=${productId}&goodsId=${goodsId}`;
    if(isShelf) {
      url = `${QMConst.HOST}/goods/delShelf?productId=${productId}`;
    }

    fetch(url)
      .then((res) => {
        this.setState({
          isShelf: !isShelf
        }, () => {
          // 如果是收藏状态发生变更，并且是通过收藏点进来的，就刷新dataList
          if(this.props.source == 'shelf') {
            msg.emit('dataList:refresh', 'goods/shelfList');
          }
        });
      })
  },


  /**
   * 获取采购单数据
   * @param submitData
   * @param total
   * @private
   */
  _getShoppingCartData() {
    var submitData = [];
    var total = 0;
    var shoppingCart = this.refs.specList.getShoppingCart();

    if (__DEV__) {
      console.log('采购单meta数据:', shoppingCart);
    }

    var specStr = this.state.skuProps.join('-');
    for (var item in shoppingCart) {
      if (shoppingCart.hasOwnProperty(item)) {
        var sku = this._allSkuCache[specStr ? specStr + '-' + item : item];
        var buyCount = shoppingCart[item];
        if (sku && buyCount && buyCount != 'null') {
          total += buyCount;
          submitData.push({
            id: sku.skuId,
            itemNum: buyCount
          })
        }
      }
    }

    var result = {};
    result["total"] = total;
    result["submitData"] = submitData;
    return result;
  },


  /**
   * 切换规格
   * @param index
   * @param vid
   * @private
   */
  _handleSelectSpec(index, vid) {

    var skuProps = this.state.skuProps.slice();
    if (skuProps[index] == vid) {
      return;
    }

    // 如果切换前有输入购买数量，询问是否要加入采购单
    var result = this._getShoppingCartData();
    if (parseInt(result["total"]) > 0) {
      Alert.alert(
        '添加到采购单',
        '您需要先将商品加入采购单吗?',
        [
          {text: '取消', onPress: () => {
            this._selectSpec(skuProps, index, vid);
          }},
          {text: '确定', onPress: () => {
            if (__DEV__) {
              console.log('提交的数据:', result["submitData"]);
            }

            fetch(`${QMConst.HOST}/cart/add`, {
              method: 'POST',
              body: JSON.stringify(result["submitData"])
            }).then((res) => {
              msg.emit('app:tip', '成功加入采购单');
              this._selectSpec(skuProps, index, vid);
            }).catch(() => {
              msg.emit('app:tip', '操作失败，请重试');
            });
          }}
        ]
      )
    }else{
      this._selectSpec(skuProps, index, vid);
    }
  },

  /**
   * 点击后的操作
   * @private
   */
  _selectSpec(skuProps, index, vid){

    skuProps[index] = vid;

    if (__DEV__) {
      console.log('选定规格,index: %s, vid: %s', index, vid);
      console.log('当前所有的规格组合的cache:');
      console.table(this._cache);
    }

    var skuLastProps = this._filterSkuLastSpecList(skuProps);

    if (__DEV__) {
      console.log('当前的sku组合：', skuProps);
      console.log('最后一个规格的可选值:', skuLastProps);
    }

    // 缓存sku组合
    var skus = [];
    var spec_str = skuProps.join('-');
    skuLastProps.forEach((_, k) => {
      skus[k] = this._allSkuCache[spec_str + '-' + skuLastProps[k]];
      skus[k].buyCount = 0;
    });

    var props = this.state.specs;
    var enableSpec = new Array();

    // 设置禁用规格
    props = this._setSpecDisable(skuProps, skuLastProps, props, enableSpec);

    this.setState({
      skuProps: skuProps,
      skuLastProps: skuLastProps,
      skus: skus,
      specs: props,
      enableSpec: enableSpec
    });
  },


  /**
   * 设置禁用规格
   * @param skuProps
   * @param skuLastProps
   * @param props
   * @returns {*}
   * @private
   */
  _setSpecDisable(skuProps, skuLastProps, props, enableSpec) {

    // 选中的  X1, X2, X3
    skuProps.forEach((checkSpec, checkSpec_index) => {

      var prop = props[checkSpec_index];

      var slist = prop.slist;// v1 , v2, v3

      slist.forEach((specVal_, specVal_index) => {
        var specVal = specVal_.svid;

        // specVal = 美国， specVal_index ＝1
        var specVal_Array = new Array();

        skuProps.forEach((checkSpec_s, checkSpec_s_index) => {

          if (checkSpec_s_index < checkSpec_index) {
            specVal_Array.push(checkSpec_s)
          }


          if (checkSpec_index == checkSpec_s_index) {
            specVal_Array.push(specVal);
          }

          if (checkSpec_s_index > checkSpec_index) {
            specVal_Array.push(checkSpec_s)
          }

        });

        var specVal_ArrayStr = specVal_Array.join('-');
        var select_specVal_ArrayStr = skuProps.join('-');

        var disable = 0;
        skuLastProps.forEach((_, k) => {

          var skuObj = this._allSkuCache[specVal_ArrayStr + '-' + skuLastProps[k]];
          if (skuObj && skuObj.disable) {
            disable = 1;
          }
        });
        specVal_.disable = disable;

        // 只存储当前选中的可用规格集合
        if (specVal_ArrayStr == select_specVal_ArrayStr && disable) {
          enableSpec.push(specVal_);
        }
      });

    });

    return props;
  },

  /**
   * 过滤出最后一个规格的可选值
   */
  _filterSkuLastSpecList(skuSpecButLast) {
    return this._cache.filter(v => {
      return v.join('-').indexOf(skuSpecButLast.join('-')) != -1;
    }).map(v => v[v.length - 1]);
  },


  /**
   * 刷新商品详情购物车数量
   */
  _handleRefreshCount(){
    fetch(`${QMConst.HOST}/cart/count`)
      .then((res) => this.setState({cartCount: res}));
  }
});


var styles = StyleSheet.create({
  innerContainer: {
    flex: 1,
    backgroundColor: '#FFF',
    justifyContent: 'center'
  },
  listRow: {
    paddingTop: 15,
    paddingRight: 10,
    paddingBottom: 10,
    paddingLeft: 10,
    flexDirection: 'row',
    justifyContent: 'space-between',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#e1e1e1'
  },
  img: {
    marginTop: 5,
    marginRight: 10,
    width: 60,
    height: 60,
    borderWidth: 1 / PixelRatio.get(),
    borderColor: '#ebebeb'
  },
  detail: {
    flex: 1
  },
  proText: {
    fontSize: 14,
    paddingBottom: 2,
    height: 34,
    lineHeight: 16,
    color: '#333',
    overflow: 'hidden'
  },
  proCart: {
    marginTop: 5,
    paddingBottom: 3
  },
  priceText: {
    fontSize: 16,
    color: '#ff8a00'
  }
});


module.exports = GoodsDetail;
